<template>
	<el-dialog
		:title="titleMap[mode]"
		v-model="visible"
		:width="500"
		destroy-on-close
		@closed="$emit('closed')"
	>
		<el-form
			:model="form"
			:rules="rules"
			:disabled="mode == 'show'"
			ref="dialogForm"
			label-width="100px"
			label-position="left"
		>
			<el-form-item label="登录密码" prop="password">
				<el-input
					type="password"
					v-model="form.password"
					clearable
					show-password
				></el-input>
			</el-form-item>
			<el-form-item label="确认密码" prop="password2">
				<el-input
					type="password"
					v-model="form.password2"
					clearable
					show-password
				></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button
				v-if="mode != 'show'"
				type="primary"
				:loading="isSaveing"
				@click="submit()"
				>保 存</el-button
			>
		</template>
	</el-dialog>
</template>

<script>
export default {
	emits: ["success", "closed"],
	data() {
		return {
			mode: "change",
			userIds: [],
			titleMap: {
				change: "修改密码",
			},
			visible: false,
			isSaveing: false,
			//表单数据
			form: {
				userId: "",
				password: "",
			},
			//验证规则
			rules: {
				password: [
					{ required: true, message: "请输入登录密码" },
					{
						validator: (rule, value, callback) => {
							if (this.form.password2 !== "") {
								this.$refs.dialogForm.validateField(
									"password2"
								);
							}
							callback();
						},
					},
				],
				password2: [
					{ required: true, message: "请再次输入密码" },
					{
						validator: (rule, value, callback) => {
							if (value !== this.form.password) {
								callback(new Error("两次输入密码不一致!"));
							} else {
								callback();
							}
						},
					},
				],
			},
		};
	},
	mounted() {},
	methods: {
		//显示
		open() {
			this.visible = true;
			return this;
		},
		//表单提交方法
		submit() {
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					for (var index = 0; index < this.userIds.length; index++) {
						await this.$API.user.changePassword.post({
							userId: this.userIds[index].userId,
							password: this.form.password,
						});
					}

					this.isSaveing = false;
					this.visible = false;
					this.$message.success("操作成功");
					// if (res.code == 200) {

					// } else {
					// 	this.$alert(res.message, "提示", { type: "error" });
					// }
				} else {
					return false;
				}
			});
		},
		//表单注入数据
		setData(data) {
			this.userIds = data;
		},
	},
};
</script>

<style></style>
